from ninja import NinjaAPI, Schema
from ninja.security import HttpBearer
from django.forms.models import model_to_dict
from jz.models import LoginInfo, Setting, TaskDayReport, TaskStates, TaskWant, TaskType
import jz.func as jz_func
import os
from django.db.models import Sum  # 引入

class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        if token == "supersecret":
            return token

# jz_api = NinjaAPI(auth=GlobalAuth())
jz_api = NinjaAPI()

class Set(Schema):
    name: str
    

# 转字典
def dtol(x):
    return [model_to_dict(i) for i in x]

def ltol(x):
    return [i for i in x]

@jz_api.get("/get{name}") # 取得数据
def api_get(request,name:str,key:str=None):
    if name == 'logininfo': # 设置 初始化 页面用
        if key:
            return {"data": model_to_dict(LoginInfo.objects.get(key=key))}
        return {"data":[i for i in LoginInfo.objects.values('key','city_name','used_team','team_name','real_name','username','password','remark')]}
    if name == 'vars': # 设置变量
        if key:
            return {"data": model_to_dict(Setting.objects.get(key=key))}
        res = dtol(Setting.objects.all())
        res.append({"key":"root_path","value":os.path.expanduser('~'),"remark":"用户目录"})
        return {"data":res}
    if name == 'tasktype': # 取到任务类型
        if key:
            return {"data": model_to_dict(TaskType.objects.get(key=key))}
        res = dtol(TaskType.objects.all())
        return {"data":res}
    if name == 'task': # 获取此账号目前首页能看到的任务信息
        res = jz_func.search_task(city_id=key)
        return {"data":res}
    if name == 'team':
        res = ltol(LoginInfo.objects.order_by('used_team').values('key','city_name','team_name','used_team','real_name'))
        city_names = ltol(LoginInfo.objects.values('city_name').distinct())
        return {"data":res, "city_names":city_names}
    if name == 'taskinfo':
        return {"data": [i for i in TaskStates.objects.filter(leftNum__gt='0').values('taskName','cityId','createTime','totalNum','finishNum','leftNum','per','upDate').order_by('cityId', 'per')]}
    if name == 'teamtaskinfo':
        res = jz_func.up_task(key)
        return {"data": res}
    return {"not a app":name}


@jz_api.get("/uplogininfo")
def uplogininfo(request,key,city_name,used_team,team_name,real_name,username,password,remark):
    LoginInfo.objects.filter(key=key).update(city_name=city_name,used_team=used_team,team_name=team_name,real_name=real_name,username=username,password=password,remark=remark)
    return {"state":"ok"}

@jz_api.get("/dellogininfo")
def dellogininfo(request,key):
    LoginInfo.objects.filter(key=key).delete()
    return {"state":"ok"}

@jz_api.get("/inslogininfo")
def inslogininfo(request,key,city_name,used_team,team_name,real_name,username,password,remark):
    LoginInfo.objects.create(key=key,city_name=city_name,used_team=used_team,team_name=team_name,real_name=real_name,username=username,password=password,remark=remark)
    return {"state":"ok"}

@jz_api.get("/delvars")
def delvars(request,key):
    Setting.objects.filter(key=key).delete()
    return {"state":"ok"}

@jz_api.get("/upvars")
def upvars(request,key,value,remark):
    Setting.objects.filter(key=key).update(value=value,remark=remark)
    return {"state":"ok"}

@jz_api.get("/uptasktype")
def uptasktype(request,key,textKey):
    TaskType.objects.filter(key=key).update(textKey=textKey)
    return {"state":"ok"}

@jz_api.get("/insvars")
def insvars(request,key,value,remark):
    Setting.objects.create(key=key,value=value,remark=remark)
    return {"state":"ok"}


@jz_api.get("/searchphone")
def searchphone(request,city_id,startdate,phone='',enddate='',handleResult='',taskName='',deptName='',isConn=''):
    # 外呼明细查询API
    res = jz_func.search_phone(city_id,phone,startdate,enddate,handleResult,taskName,deptName,isConn)
    return {"data":res['content']['rows'],"totalRows":res['content']['totalRows']} if res['success']==True else {"data":"error"}

@jz_api.get("/report/downloadreport")
def downloadreport(request,city_id,startdate,enddate='',handleResult='',taskName='',deptName='',isConn='',remark=''):
    # 外呼明细下载API
    enddate = f'{enddate} 23:00:00' if enddate != '' else f'{startdate} 23:00:00'
    res = jz_func.jz_download_exl(city_id,startTimeBegin=f'{startdate} 00:00:00',startTimeEnd=enddate,deptName=deptName,taskName=taskName,handleResult=handleResult,isConn=isConn,remark=remark)
    return {"data":res}

@jz_api.get("/report/openexl")
def openexl(request, exl_path, is_path=False):
    if is_path:
        os.startfile(exl_path)
        return {"data":'ok'}
    else:
        os.startfile(jz_func.CONFIG_SET[exl_path])
        # print(exl_path)
        return {"data":'ok'}

@jz_api.get("/report/jk")
def jiankong(request,now_date,team_list):
    res = jz_func.jiankong(now_date,city_ids=list(filter(None,team_list.split('#'))))
    return {"data":res}

@jz_api.get("/report/gj")
def html_to_gj(request):
    jz_func.html_to_gj()
    return {"data":'ok'}

@jz_api.get("/report/tb")
def html_to_gj(request,now_date,team_list,city_name,output_path=None):
    jz_func.output_xl(now_date,list(filter(None,team_list.split('#'))),city_name)
    return {"data":'ok'}

@jz_api.get("/report/upcallreport")
def upcallreport(request,now_date):
    # 更新日外呼明细
    res = jz_func.upcallreport1(now_date,is_all=1)
    return {"data":res}

@jz_api.get("/report/lkh") # 撸开户
def lkh(request, updayreport=False):
    if updayreport:
        jz_func.updateKhToDayreport()
        return {"data":'ok'}
    jz_func.l_kh()
    return {"data":'ok'}

@jz_api.get("/report/autooutputxl") # 自动填表
def autooutputxl(request,now_date, city_name, is_temp=False):
    if is_temp:
        if city_name == '宜昌':
            jz_func.output_xl(now_date, ['yc1','yc2','yc3','yc4'], city_name, is_temp=True)
        if city_name == '襄阳':
            jz_func.output_xl(now_date, ['xy1','xy2','xy3','xy4'], city_name, is_temp=True)
    else:
        if city_name == '宜昌':
            jz_func.output_xl(now_date, ['yc'], city_name,is_zn=True)
        if city_name == '襄阳':
            jz_func.output_xl(now_date, ['xy'], city_name,is_zn=True)
        # city_ids = list(filter(None,team_list.split('#')))
        # jz_func.output_xl(now_date, city_ids, city_name, input_path='/Users/fei/Desktop/宜昌联通电话外呼营销日报表-湖北话加2021年11月.xlsx',is_zn=is_zn)
    return {"data":'ok'}

@jz_api.get("/report/ljk") # 撸监控的csv文件
def ljk(request):
    jz_func.ljz_from_csv()
    return {"data":'ok'}

@jz_api.get("/report/jkzn") # 撸智能
def jkzn(request, city_id, nowdate):
    jz_func.jk_zn(city_id, nowdate)
    return {"data":'ok'}

@jz_api.get("/report/upecharts")
def up_echarts(request):
    # 刷新图表
    jz_func.up_echarts()
    return {"data":'ok'}

@jz_api.get("/report/lu") # 撸文件
def lu(request,file_form,file_to):
    res = jz_func.l_jz(file_form)
    res.to_excel(file_to)
    return {"data":'ok'}


@jz_api.get("/report/update_lx") # 更新电话购首充情况
def lx(request, city_name):
    jz_func.update_lx(city_name, '6')
    return {"data":'ok'}